#include "font.h"
#include "sprite.h"
#include "core.h"

font::font(const char* _fname,color _color,float _scle)
{
	m_render = core::get_inst().get_render();
	m_charset.clear();
	m_color = _color;
	xml_document xml;
	xml.parse_file(_fname);

	char* fname = (char*)_fname;

	for(u32 i=(u32)strlen(_fname);i>=0;i--)
	{
		if(fname[i]=='\\')
		{
			fname[i]=0;
			break;
		}
	}

	string path = fname;
	path+="\\";
	path+=xml["Font"].attr_str("texture");

	m_texture = m_render->create_texture(8,8,dxt1);
	m_tex_w = (float)(xml["Font"].attr_int("width"));
	m_tex_h = (float)(xml["Font"].attr_int("height"));
	for(u32 i=0;i<xml["Font"].child_count();i++)
	{
		xml_node& n=xml["Font"][i];
		if(string(n.name())=="Char")
		{
			char  ch = n.attr_int("char");
			float tu = (float)(n.attr_int("tu"))/m_tex_w;
			float tv = (float)(n.attr_int("tv"))/m_tex_h;
			float tw = (float)(n.attr_int("tw"))/m_tex_w;
			float th = (float)(n.attr_int("th"))/m_tex_h;
			float a = (float)(n.attr_int("a"))/m_tex_w;
			float c = (float)(n.attr_int("c"))/m_tex_h;
			m_charset[ch]=ch_rect(tu,tv,tw,th,a,c);
		}
	}
}

font::~font()
{
	delete m_texture;
}

void font::print(float _x,float _y,float _z,const char* _text,...)
{
	float total_x = 0.0f;
	m_render->set_cullmode(cullmode_none);
	/*D3DCHECK(m_render->get_device()->SetRenderState(D3DRS_ALPHABLENDENABLE, true));
	m_render->set_texture(0,m_texture);
	D3DCHECK(m_render->get_device()->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1));
	for(u32 i=0;i<strlen(_text);i++)
	{
		ch_rect& s = m_charset[_text[i]];
		float w = m_tex_w*s.tw;
		float h = m_tex_h*s.th;
		sprite_vrt vrt []={{total_x+_x,     _y+h, _z,1.0f,m_color.argb(),s.tu,	    s.tv+s.th},
						   {total_x+_x,     _y,	  _z,1.0f,m_color.argb(),s.tu,	    s.tv	 },
						   {total_x+_x+w,   _y+h, _z,1.0f,m_color.argb(),s.tu+s.tw, s.tv+s.th},
						   {total_x+_x+w,   _y,	  _z,1.0f,m_color.argb(),s.tu+s.tw, s.tv	 }};

		D3DCHECK(m_render->get_device()->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,vrt,sizeof(sprite_vrt)));
		total_x+=s.tw*m_texture->m_width;
	}
	D3DCHECK(m_render->get_device()->SetRenderState(D3DRS_ALPHABLENDENABLE, false));*/
}